package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.domain.SystemMenu;
import cn.wolfcode.wms.mapper.SystemMenuMapper;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SystemMenuServiceImpl implements ISystemMenuService {
    @Autowired
    private SystemMenuMapper systemMenuMapper;
    @Override
    public void saveOrUpdate(SystemMenu entity) {
        //判断id是否为空,Optional是JDK1.8新特性
        if (!Optional.ofNullable(entity.getId()).isPresent()) {
            systemMenuMapper.insert(entity);
        }else {
            systemMenuMapper.updateByPrimaryKey(entity);
        }
    }

    @Override
    public void delete(Long id) {
        systemMenuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public SystemMenu get(Long id) {
        return systemMenuMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SystemMenu> list() {
        return systemMenuMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        Integer rows = systemMenuMapper.selectForCount(qo);
        if (rows == 0) {
            return PageResult.EMPTY_PAGE;
        }
        List<?> data = systemMenuMapper.selectForList(qo);
        PageResult result = new PageResult(qo.getCurrentPage(),qo.getPageSize(),rows,data);
        return result;
    }

    @Override
    public List<SystemMenu> getParentMenus(Long parentId) {
        List<SystemMenu> menus = new ArrayList<>();
        SystemMenu menu = systemMenuMapper.selectByPrimaryKey(parentId);
        menus.add(menu);
        //递归添加子菜单,直至不再有子菜单为止
        while (Optional.ofNullable(menu.getParent()).isPresent()){
            menu = menu.getParent();
            menus.add(menu);
        }
        //以上添加方式是由子菜单回溯至父菜单,是倒序的,需颠倒前后位置
        Collections.reverse(menus);
        return menus;
    }

    @Override
    public List<Map<String, Object>> getMenusBySn(String menuSn) {
        List<Map<String, Object>> menus = null;
        //超管则显示所有的权限
        Employee emp = UserContext.getCurrentUser();
        if (emp.isAdmin()) {
            menus = systemMenuMapper.selectMenusBySn(menuSn);
        }else {
            //非超管根据员工拥有的角色去查询应显示的菜单
            menus = systemMenuMapper.selectMenusBySnAndEmployeeId(menuSn,emp.getId());
        }
        return menus;
    }
}
